//
//  PHTextView.m
//  LuQu
//
//  Created by xp on 2017/9/19.
//  Copyright © 2017年 mingthink. All rights reserved.
//

#import "PHTextView.h"
@interface PHTextView ()<UITextViewDelegate>
{
    UILabel *placeholderLabel;
}
@end
@implementation PHTextView

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        
        [self setup];
    }
    return self;
}

-(instancetype)init{
    if (self = [super init]) {
        [self setup];
    }
    return self;
}

-(instancetype)initWithCoder:(NSCoder *)aDecoder{
    if (self = [super initWithCoder:aDecoder]) {
        [self setup];
    }
    return self;
}
-(void)awakeFromNib
{
    [super awakeFromNib];
    [self setup];
}
- (void)setup {
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textDidChangeNotification:) name:UITextViewTextDidChangeNotification object:self];
    //[self addObserver:self forKeyPath:@"contentSize"options:NSKeyValueObservingOptionNew context:NULL];
    //float left=5,top=8,hegiht=0;
    
    currentLine = 1;
    //    [[NSNotificationCenter defaultCenter] addObserver:self
    //                                             selector:@selector(didReceiveTextDidChangeNotification:)
    //                                                 name:UITextViewTextDidChangeNotification
    //                                               object:self];
    //
    //    _placeholderColor = [UIColor lightGrayColor];
    //    self.autoresizingMask = UIViewAutoresizingFlexibleWidth;
    //    self.scrollIndicatorInsets = UIEdgeInsetsMake(10.0f, 0.0f, 10.0f, 0.0f);
    //self.contentInset = UIEdgeInsetsZero;
    //    self.scrollEnabled = YES;
    //    self.scrollsToTop = NO;
    //self.userInteractionEnabled = YES;
    //self.font = [UIFont systemFontOfSize:16.0f];
    //self.textColor = [UIColor blackColor];
    //self.backgroundColor = [UIColor whiteColor];
    //    self.keyboardAppearance = UIKeyboardAppearanceDefault;
    //    self.keyboardType = UIKeyboardTypeDefault;
    //    self.returnKeyType = UIReturnKeyDefault;
    //    self.textAlignment = NSTextAlignmentLeft;
    //self.textContainer.lineBreakMode = NSLineBreakByCharWrapping;
    //self.layoutManager.allowsNonContiguousLayout = NO;//UITextView 中的 layoutManager(NSLayoutManager) 的是否非连续布局属性，默认是 YES，设置为 NO 后 UITextView 就不会再自己重置滑动了
    self.delegate = self;
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary*)change context:(void *)context
{
    UITextView *mTrasView = object;
    
    CGFloat topCorrect = (self.size.height - self.contentSize.height);
    
    topCorrect = (topCorrect <0.0 ?0.0 : topCorrect);
    
    self.contentOffset = (CGPoint){.x =0, .y = -topCorrect/2};
    
}
-(void)layoutSubviews{
    [super layoutSubviews];
    [placeholderLabel sizeToFit];
    
    if (_verticalCenterPlaceholder) {
        placeholderLabel.frame=CGRectMake(8, (self.height-CGRectGetHeight(placeholderLabel.frame))/2, CGRectGetWidth(self.frame)-16, CGRectGetHeight(placeholderLabel.frame));
    }else{
        placeholderLabel.frame=CGRectMake(8, 8, CGRectGetWidth(self.frame)-16, CGRectGetHeight(placeholderLabel.frame));
    }
    
}
-(void)setPlaceholderFont:(UIFont *)placeholderFont
{
    _placeholderFont=placeholderFont;
    placeholderLabel.font=placeholderFont;
}
-(void)setFont:(UIFont *)font
{
    [super setFont:font];
    placeholderLabel.font=self.placeholderFont?self.placeholderFont:self.font;
}
-(void)setPlaceholderColor:(UIColor *)placeholderColor
{
    _placeholderColor=placeholderColor;
    placeholderLabel.textColor=placeholderColor;
}
-(void)setPlaceholder:(NSString *)placeholder{
    _placeholder=placeholder;
    if (placeholderLabel == nil){
        placeholderLabel=[[UILabel alloc] init];
        //placeholderLabel.autoresizingMask = (UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight);
        placeholderLabel.lineBreakMode = NSLineBreakByWordWrapping;
        placeholderLabel.textColor=[UIColor lightGrayColor];
        placeholderLabel.font=self.font;
        placeholderLabel.backgroundColor = [UIColor clearColor];
        placeholderLabel.numberOfLines = 0;
        if (_horizontalCenterPlaceholder) {
            placeholderLabel.textAlignment=NSTextAlignmentCenter;
        }
        [self addSubview:placeholderLabel];
    }
    placeholderLabel.text=_placeholder;
    
    [self refreshPlaceholder];
}
-(void)setText:(NSString *)text
{
    [super setText:text];
    [self textDidChangeNotification:nil];
}
-(void)setHorizontalCenterPlaceholder:(BOOL)horizontalCenterPlaceholder{
    _horizontalCenterPlaceholder=horizontalCenterPlaceholder;
    if (_horizontalCenterPlaceholder) {
        self.textContainerInset = UIEdgeInsetsMake(10, 0, 10, 0);
        placeholderLabel.textAlignment=NSTextAlignmentCenter;
    }
}
-(void)setVerticalCenterPlaceholder:(BOOL)verticalCenterPlaceholder{
    _verticalCenterPlaceholder=verticalCenterPlaceholder;
    if (_verticalCenterPlaceholder) {
        
    }
}
-(void)textDidChangeNotification:(NSNotification*)notification{
    
    [self refreshPlaceholder];
    
    NSInteger lines = self.contentSize.height / self.font.lineHeight;
    if (self.maxLines && lines > self.maxLines) {
        return;
    }
    
    if (currentLine != lines && self.changeLineBlock) {
        currentLine = lines;
        self.changeLineBlock(lines);
    }
}
-(void)refreshPlaceholder{
    if (self.text.length > 0) {
        placeholderLabel.hidden=YES;
    }
    else{
        placeholderLabel.hidden=NO;
    }
}

-(NSInteger)textLines{
    return self.contentSize.height / self.font.lineHeight;
}
#pragma mark ---------TextViewDelegate-------
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    if ([text isEqualToString:@"\n"]){
        return false;
    }
    
    if(range.length == 0 && _maxCount > 0){
        NSString *resultText = [textView.text stringByAppendingString:text];
        if (resultText.length > _maxCount) {
            [WToast showWithText:[NSString stringWithFormat:@"不能超过%ld个字符",_maxCount] gravity:kWTGravityTop];
            return false;
        }
    }
    return YES;
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end
